﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Ipc;

namespace iPdf
{
    class TaskProcessor
    {

        /// <summary>
        /// This is run by the first instance of the program in order
        /// to accept information from later instances using the
        /// .NET Framework's IPC mechanism.
        /// </summary>
        public static void Listen()
        {
            IpcServerChannel serverChannel = new IpcServerChannel(Global.IpcChannelName);
            ChannelServices.RegisterChannel(serverChannel, false);

            RemoteMessage remoteMessage = new RemoteMessage();
            RemotingServices.Marshal(remoteMessage, Global.RemotingServiceName);
        }

        /// <summary>
        /// This is used by later instances of the program when
        /// executed from the shell's context menu to pass along
        /// the path of a file that will be uploaded. This message
        /// is passed using the .NET Framework's IPC mechanism.
        /// </summary>
        /// <param name="args">The arguments of the instance</param>
        public static void Notify(Task task)
        {
            if (task == null)
            {
                return;
            }

            try
            {
                IpcClientChannel clientChannel = new IpcClientChannel();
                ChannelServices.RegisterChannel(clientChannel, false);

                RemoteMessage message = (RemoteMessage)Activator.GetObject(typeof(RemoteMessage), Global.IpcURL);

                if (!message.Equals(null))
                {
                    RemoteMessage.SendMessage(task);
                }
            }
            catch (RemotingException e)
            {
                string errorMsg = Helper.GenerateErrorReport(e.Message);
            }
        }
    }
}
